package org.kaiwo.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import  org.kaiwo.util.SignUtil;

/**
 * Created by chensk on 2018/8/4.
 * 愿我出走半生,归来仍是少年
 * 支付回调
 */
@WebServlet("/return")
public class ReturnServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException {
        TreeMap<String, String> map = new TreeMap<String, String>();

        Enumeration em = request.getParameterNames();

        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getParameter(name);
            map.put(name,value);

        }
        String transCode = map.remove("transCode");
        String signature = map.remove("sign");
        StringBuffer sb = new StringBuffer();
        for (Map.Entry key : map.entrySet()) {
            sb.append(key.getKey() + "=" + key.getValue() + "&");
        }
        String string = sb.substring(0, sb.length() - 1);

        try {
            if(SignUtil.validate(string,request.getParameter("sign"))&&request.getParameter("oriRespCode").equals("0000")){
              //成功逻辑

            }else{
               //失败逻辑
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }

    }


}
